#include <iostream>
#include <memory>

#include "Listener.hpp"
#include "Log.hpp"
#include "Reactor.hpp"
#include "HandlerConnection.hpp"
#include "EchoService.hpp"

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " local-port" << std::endl;
        exit(0);
    }
    uint16_t port = std::stoi(argv[1]);
    InetAddr localaddr("0.0.0.0", port);

    Echo service;

     // 专门用来处理新连接到来的模块
     Listener listener(port); // 连接管理器

     HandlerConnection handler(std::bind(&Echo::EchoService, &service, std::placeholders::_1));        // IO处理器

     // 主模块：Reactor事件派发
     std::unique_ptr<Reactor> R = std::make_unique<Reactor>();

     R->SetOnConnect(std::bind(&Listener::Accepter, &listener, std::placeholders::_1));
     R->SetOnNormalHandler(
            std::bind(&HandlerConnection::HandlerRecver, &handler, std::placeholders::_1),
            std::bind(&HandlerConnection::HandlerSender, &handler, std::placeholders::_1),
            std::bind(&HandlerConnection::HandlerExcepter, &handler, std::placeholders::_1)
     );

     R->AddConnection(listener.ListenSockfd(), EPOLLIN|EPOLLET, localaddr, ListenConnection);

     R->Dispatcher();

     return 0;
}